import { Icon } from "@iconify/react"
import { Button, Flex, Tag } from "antd"
import dayjs from "dayjs"
import { FC, useCallback, useEffect, useMemo, useState } from "react"
import { useSelector } from "react-redux"

import { queryBasicInfo, queryMemberRemarkList } from "@/api/member"
import { IUserInfo } from "@/api/member/types"
import { IMemberParams } from "@/api/risk/types"
import { DataList } from "@/components/common"
import { Toast } from "@/components/messages"
import { useDigital, usePagination } from "@/hooks"
import { UserState } from "@/interface/user/user"
import { FormatMessageProps, useLocale } from "@/locales"
import { mappingBusinessModel } from "@/utils"

import { MemberDetailModal } from "./components/MemberDetailModal"
import { ActionsContainer, BasicInfoContainer, ContentContainer, UserInfoContainer } from "./styles"
import { columnsRemarks } from "./TableInfo"

export const getAccountStatusAndContent = (row: any, f: FormatMessageProps): { type: any; text: string }[] => {
	const statusTags = []
	if (!row?.loginLockStatus && !row?.paymentLockStatus && !row?.gameLockStatus) {
		statusTags.push({
			type: "success",
			text: f({ id: "common.account_status_normal" })
		})
	}

	if (row?.gameLockStatus === 1) {
		statusTags.push({
			type: "processing",
			text: f({ id: "common.game_lock_status" })
		})
	}

	if (row?.paymentLockStatus === 1) {
		statusTags.push({
			type: "warning",
			text: f({ id: "common.account_lock_status" })
		})
	}

	if (row?.loginLockStatus === 1) {
		statusTags.push({
			type: "error",
			text: f({ id: "common.login_lock_status" })
		})
	}
	return statusTags
}

interface IButtonPermission {
	visible: boolean
	disableKey?: number
}

const useGetButtonsPermission = () => {
	const permission = useSelector((state: { user: UserState }) => state.user.permissions) || []
	const defaultPermission = {
		accountStatus: { visible: false },
		phoneNumber: { visible: false, disableKey: 4 },
		dateOfBirth: { visible: false, disableKey: 3 },
		nickName: { visible: false, disableKey: 8 },
		userName: { visible: false, disableKey: 1 },
		gender: { visible: false, disableKey: 2 },
		mailBox: { visible: false, disableKey: 5 },
		accountRemarks: { visible: false },
		loginPasswordReset: { visible: false, disableKey: 7 },
		creditRating: { visible: false },
		withdrawalPasswordReset: { visible: false, disableKey: 10 },
		bmhAccUnbind: { visible: false, disableKey: 11 }
	}
	permission.forEach((per: string) => {
		if (per === "101033") defaultPermission.accountStatus.visible = true
		if (per === "101037") defaultPermission.phoneNumber.visible = true
		if (per === "101036") defaultPermission.dateOfBirth.visible = true
		if (per === "90060045") defaultPermission.nickName.visible = true
		if (per === "101038") defaultPermission.userName.visible = true
		if (per === "101039") defaultPermission.gender.visible = true
		if (per === "101045") defaultPermission.mailBox.visible = true
		if (per === "101046") defaultPermission.accountRemarks.visible = true
		if (per === "101057") defaultPermission.loginPasswordReset.visible = true
		if (per === "101047") defaultPermission.creditRating.visible = true
		if (per === "90150024") defaultPermission.withdrawalPasswordReset.visible = true
		if (per === "90810065") defaultPermission.bmhAccUnbind.visible = true
	})
	return defaultPermission as Record<string, IButtonPermission>
}

const GENDER_TYPE = {
	[0]: "女",
	[1]: "男"
}

export const BasicInfo: FC<{
	data: IMemberParams
}> = ({ data }) => {
	const [userInfo, setUserInfo] = useState<IUserInfo | null>(null)
	const [dataRemark, setDataRemark] = useState<any>({})
	const { formatMessage, newFormat } = useLocale()
	const { renderFormat } = useDigital()
	const buttonPermissions = useGetButtonsPermission()
	const auditList = useMemo(() => {
		if (userInfo)
			return userInfo.auditList.map(ele => {
				return ele.applyType
			})
		return []
	}, [userInfo])

	const [modalValue, setModalValue] = useState<any>(null)

	const { pagination, onPageChange } = usePagination(100)

	const handleGetMemberRemarkList = useCallback(
		async (isRefresh?: boolean) => {
			const resultParam = {
				merchantId: data.merchantId,
				userName: data.username,
				topProxyName: data.username,
				userId: data.userId,
				currency: data.currency,
				clubId: data.clubId,
				businessModel: data.businessModel,
				...pagination
			}

			const [err, remarkListRes] = await queryMemberRemarkList(!isRefresh ? { ...resultParam } : { ...resultParam, pageNum: 1 })
			if (!err) setDataRemark(remarkListRes)
		},
		[data, pagination]
	)
	const handleGetUserInfo = useCallback(async () => {
		const tempParam = {
			...(data.merchantId ? { merchantId: data.merchantId } : {}),
			...(data.realName ? { realName: data.realName } : {}),
			...(data.mail ? { mail: data.mail } : {}),
			...(data.phoneNumber ? { phoneNo: `${data.phoneNoPrefix}-${data.phoneNumber}` } : {}),
			...(data.userName ? { userName: data.userName } : {})
		}

		const [err, basicInfoRes] = await queryBasicInfo(tempParam)
		if (err) Toast.error(err.msg)

		setUserInfo(basicInfoRes)
	}, [data])

	useEffect(() => {
		if (data.userId) handleGetMemberRemarkList()
	}, [pagination])

	useEffect(() => {
		// this will help to refresh pagination when upper actions are changed
		if (data.userId) handleGetMemberRemarkList(true)
	}, [data])

	useEffect(() => {
		handleGetUserInfo()
	}, [])

	const handelDayNum = (val: string) => {
		if (val) {
			const lastTime = dayjs(val)
			const nowTime = new Date()
			const day = dayjs(nowTime).diff(lastTime, "day")
			return `${day} ${formatMessage({ id: "common.day" })}`
		} else {
			return "-"
		}
	}

	const handleCancel = () => {
		setModalValue(null)
		handleGetMemberRemarkList(true)
		handleGetUserInfo()
	}

	const tagsStatus = getAccountStatusAndContent(userInfo, formatMessage)

	return (
		<BasicInfoContainer>
			<ActionsContainer>
				<Button>{formatMessage({ id: "member.tabs.basic_info" })}</Button>
				<Button
					type="primary"
					onClick={() => {
						handleGetMemberRemarkList(true)
						handleGetUserInfo()
					}}
					icon={<Icon icon="solar:refresh-outline" fontSize="1.2rem" />}
				>
					{formatMessage({ id: "member.refresh" })}
				</Button>
				<div className="edit-title">
					<Icon icon="la:edit-solid" fontSize="1.2rem" />
					<span>{formatMessage({ id: "label.edit" })}</span>
				</div>
				<Flex gap={10} wrap="wrap">
					{Object.entries(buttonPermissions)
						.filter(([, value]) => value.visible)
						.map(([key, value]) => {
							const mess = `member.button_permissions.${key}`
							const title = formatMessage({ id: mess })
							const disable = value.disableKey ? auditList.includes(value.disableKey) : false
							return (
								<Button
									type="primary"
									key={key}
									disabled={disable}
									onClick={() => {
										if (!disable) setModalValue(key)
									}}
								>
									{title}
								</Button>
							)
						})}
				</Flex>
				{/* MODAL */}
				{userInfo && modalValue && (
					<MemberDetailModal
						handleGetUserInfo={handleGetUserInfo}
						userInfo={userInfo}
						filterInfo={data}
						handleCancel={handleCancel}
						type={modalValue}
					/>
				)}
			</ActionsContainer>
			<ContentContainer>
				<h2>{formatMessage({ id: "member.summary_info" })}</h2>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.member_account" })}:</span>
					<span>{userInfo?.userName}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.merchant" })}:</span>
					<span>{userInfo?.merchantName}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.account_type" })}:</span>
					<span>{userInfo?.accountType === 1 ? "正式" : "-"}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.account_status" })}:</span>
					<span>
						{tagsStatus?.map(item => (
							<Tag color={item.type} key={item.text}>
								{item.text || "-"}
							</Tag>
						))}
					</span>
				</div>

				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.club_name" })}:</span>
					<span>{userInfo?.clubName || "-"}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.button_permissions.riskControlLevel" })}:</span>
					<span>{userInfo?.windControlName || "-"}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.first_deposit" })}:</span>
					<span>{userInfo?.firstDepositDatetime || "-"}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.first_deposit_amount" })}:</span>
					<span>{userInfo?.firstDeposit ? renderFormat(userInfo?.firstDeposit) : "-"}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.business_model" })}:</span>
					<span>{mappingBusinessModel(userInfo?.businessModel || -1, formatMessage)}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.offline_days" })}:</span>
					<span>{handelDayNum(userInfo?.lastLoginDatetime || "")}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.register_ip" })}:</span>
					<span>{userInfo?.registerIp || "-"}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.registration_time" })}:</span>
					<span>{userInfo?.createdAt || "-"}</span>
				</div>

				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.last_login_time" })}:</span>
					<span>{userInfo?.lastLoginDatetime}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.registration_end" })}:</span>
					<span>
						{userInfo?.registerDeviceType
							? formatMessage({ id: `dict.device_type.${(userInfo?.registerDeviceType || 0) - 1}.description` })
							: "-"}
					</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.agent_account" })}:</span>
					<span>{userInfo?.topProxyName}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.superior_agent" })}:</span>
					<span>{userInfo?.parentProxyName}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.button_permissions.labelMember" })}:</span>
					{auditList.includes(6) ? (
						<span style={{ color: "#E6A23C" }}>{formatMessage({ id: "member.user_info.under_review" })}</span>
					) : (
						<span>{userInfo?.labelName || "-"}</span>
					)}
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.number_of_conversions" })}:</span>
					<span>{userInfo?.transforNum + " " + formatMessage({ id: "member.user_info.times" })}</span>
				</div>
				<div className="content-item">
					<span>{formatMessage({ id: "member.user_info.credit_rating" })}:</span>
					<span>{userInfo?.creditLevel}</span>
				</div>
			</ContentContainer>
			<UserInfoContainer>
				<h2>{formatMessage({ id: "member.personal_info" })}</h2>
				<div className="user-info-content">
					<div className="avatar">
						<img src={userInfo?.topImagesUrl} alt="avatar" />
					</div>
					<div className="info-container">
						<div className="info-item">
							<span>{formatMessage({ id: "member.user_info.real_name" })}:</span>
							{auditList.includes(1) ? (
								<span className="personal-apply-color">{formatMessage({ id: "member.user_info.under_review" })}</span>
							) : (
								<span>{userInfo?.realName || "-"}</span>
							)}
						</div>
						<div className="info-item">
							<span>{formatMessage({ id: "member.user_info.phone_num" })}:</span>
							{auditList.includes(4) ? (
								<span className="personal-apply-color">{formatMessage({ id: "member.user_info.under_review" })}</span>
							) : (
								<span>{userInfo?.mobile || "-"}</span>
							)}
						</div>
						<div className="info-item">
							<span>{formatMessage({ id: "member.bmh.bmh_id" })}:</span>
							{auditList.includes(11) ? (
								<span className="personal-apply-color">{formatMessage({ id: "member.user_info.under_review" })}</span>
							) : (
								<span>{userInfo?.bmhUserId || "-"}</span>
							)}
						</div>
					</div>
					<div className="info-container">
						<div className="info-item">
							<span>{formatMessage({ id: "member.user_info.nickname" })}:</span>
							{auditList.includes(8) ? (
								<span className="personal-apply-color">{formatMessage({ id: "member.user_info.under_review" })}</span>
							) : (
								<span>{userInfo?.nickName || "-"}</span>
							)}
						</div>
						<div className="info-item">
							<span>{formatMessage({ id: "member.user_info.date_of_birth" })}:</span>
							{auditList.includes(3) ? (
								<span className="personal-apply-color">{formatMessage({ id: "member.user_info.under_review" })}</span>
							) : (
								<span>{userInfo?.birthday || "-"}</span>
							)}
						</div>
						<div className="info-item">
							<span>{formatMessage({ id: "member.bmh.bmh_account" })}:</span>
							{auditList.includes(11) ? (
								<span className="personal-apply-color">{formatMessage({ id: "member.user_info.under_review" })}</span>
							) : (
								<span>{userInfo?.bmhUserId || "-"}</span>
							)}
						</div>
					</div>
					<div className="info-container">
						<div className="info-item">
							<span>{formatMessage({ id: "member.user_info.gender" })}:</span>
							{auditList.includes(2) ? (
								<span className="personal-apply-color">{formatMessage({ id: "member.user_info.under_review" })}</span>
							) : (
								<span>{userInfo && userInfo?.gender > 0 ? GENDER_TYPE[userInfo?.gender as 0 | 1] : "-"}</span>
							)}
						</div>
						<div className="info-item">
							<span>{formatMessage({ id: "member.user_info.mail" })}:</span>
							{auditList.includes(5) ? (
								<span className="personal-apply-color">{formatMessage({ id: "member.user_info.under_review" })}</span>
							) : (
								<span>{userInfo?.email || "-"}</span>
							)}
						</div>
					</div>
				</div>
			</UserInfoContainer>
			<h2>{newFormat("risk.label.remarks_label")}</h2>
			<DataList
				data={dataRemark.record}
				rowKey="id"
				pagination={{
					pageSize: dataRemark.pageSize,
					current: dataRemark.pageNum,
					total: dataRemark.totalRecord,
					showTotal: (total: number) => `共 ${total} 条`
				}}
				bordered
				columns={columnsRemarks(formatMessage)}
				size="middle"
				onChange={onPageChange}
			/>
		</BasicInfoContainer>
	)
}
